<template>
  <div class="ccui-app-container contract-approval">
    <div class="ccui-advanced-search-wrapper ccui-clearfix">
      <el-search
        :formProp="formData"
        @search="search"
        :isShowSearch="isShowSearch"
        class="ccui-highsearch"
        :selectClear="true"
        :isShow="isShow"
      >
        <div class="ccui-tab-wrapper">
          <el-button
            :type="isActive === index ? 'table-top-active' : 'table-top'"
            size="mini"
            v-for="(item, index) in focuses"
            :key="index"
            @click="tabChange(item.focus)"
          >
            <template v-if="item.focus === 'approvalAll' && totalNum !== null"
              >全部{{ isActive === 0 ? `(${totalNum})` : "" }}</template
            >
            <template
              v-if="item.focus === 'approvalPending' && totalNum !== null"
              >待审批{{ isActive === 1 ? `(${totalNum})` : "" }}</template
            >
            <template
              v-else-if="item.focus === 'approvalPass' && totalNum !== null"
              >已审批{{ isActive === 2 ? `(${totalNum})` : "" }}</template
            >
          </el-button>
        </div>
        <template slot="search">
          <el-input
            v-model="formData.contractName"
            clearable
            searchLabel="合同名称"
            placeholder="请输入合同名称模糊查询"
          ></el-input>
          <el-input
            v-model="formData.contractCode"
            clearable
            searchLabel="合同编号"
            placeholder="请输入合同编号模糊查询"
          ></el-input>
          <el-input
            v-model="formData.partyBName"
            clearable
            searchLabel="供应商1"
            placeholder="请输入供应商1名称模糊查询"
          ></el-input>
          <el-input
            v-model="formData.partyBNameBak"
            clearable
            searchLabel="供应商2"
            placeholder="请输入供应商2名称模糊查询"
          ></el-input>
          <el-input
            v-model="formData.reportInOrgName"
            clearable
            searchLabel="填报单位"
            placeholder="请输入填报单位模糊查询"
          ></el-input>
          <!-- <el-date-picker
            v-model="formData.compileDate"
            type="month"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            searchLabel="编制日期"
            placeholder="请选择编制日期查询"
          >
          </el-date-picker> -->
          <el-input
            v-model="formData.partyAName"
            clearable
            searchLabel="合同签订单位(甲方)"
            placeholder="请输入合同签订单位(甲方)模糊查询"
          ></el-input>
          <el-input
            v-model="formData.thirdCategoriesOfName"
            clearable
            searchLabel="分类名称"
            placeholder="请输入分类名称模糊查询"
          ></el-input>

          <el-select
            class="ccui-form-longInput"
            v-model="formData.workItemStatus"
            searchLabel="审批状态"
            placeholder="请选择审批状态查询"
          >
            <el-option
              v-for="item in jsList.contractState"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </template>
        <!-- 表单高级搜索 -->
        <el-input
          v-model="formData.contractName"
          clearable
          searchLabel="合同名称"
          placeholder="请输入合同名称模糊查询"
          slot="searchItem3"
        ></el-input>
        <el-input
          v-model="formData.contractCode"
          clearable
          searchLabel="合同编号"
          placeholder="请输入合同编号模糊查询"
          slot="searchItem1"
        ></el-input>
        <el-input
          v-model="formData.formalContractCode"
          clearable
          searchLabel="合同正式编号"
          placeholder="请输入合同正式编号模糊查询"
          slot="searchItem2"
        ></el-input>
        <el-input
          v-model="formData.partyBName"
          clearable
          searchLabel="供应商1"
          placeholder="请输入供应商1名称模糊查询"
          slot="searchItem4"
        ></el-input>
        <el-input
          v-model="formData.partyBNameBak"
          clearable
          searchLabel="供应商2"
          placeholder="请输入供应商2名称模糊查询"
          slot="searchItem5"
        ></el-input>
        <el-input
          v-model="formData.reportInOrgName"
          clearable
          searchLabel="填报单位"
          placeholder="请输入填报单位模糊查询"
          slot="searchItem6"
        ></el-input>
        <el-select
          class="ccui-form-longInput"
          v-model="formData.currencyCode"
          searchLabel="币种"
          placeholder="请选择币种查询"
          slot="searchItem7"
        >
          <el-option
            v-for="item in currencyList"
            :key="item.dicKey"
            :label="item.dicValue"
            :value="item.dicKey"
          >
          </el-option>
        </el-select>
        <el-date-picker
          v-model="formData.compileDate"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          searchLabel="编制日期"
          slot="searchItem8"
        >
        </el-date-picker>
        <el-input
          v-model="formData.partyAName"
          clearable
          searchLabel="合同签订单位(甲方)"
          placeholder="请输入合同签订单位(甲方)模糊查询"
          slot="searchItem9"
        ></el-input>
        <el-select
          class="ccui-form-longInput"
          v-model="formData.status"
          searchLabel="审批状态"
          placeholder="请选择审批状态查询"
          slot="searchItem10"
        >
          <el-option
            v-for="item in jsList.status"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <el-select
          class="ccui-form-longInput"
          v-model="formData.businessBillTypes"
          searchLabel="审批类型"
          placeholder="请选择审批类型查询"
          slot="searchItem11"
        >
          <el-option
            v-for="item in jsList.contractType"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-search>
    </div>
    <!-- 表格 -->
    <div class="ccui-multifunctional-table-wrapper">
      <el-table
        ref="multipleTable"
        :data="tableData"
        :fit="true"
        border
        class="ccui-multifunctional-table"
        @header-dragend="tableTitleWidth"
        max-height="9999"
        v-if="draggFlag"
      >
        <el-table-column label="序号" width="50" fixed>
          <template slot-scope="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="合同编号" width="170" fixed>
          <template slot-scope="scope">
            <el-button type="text" @click="goDetail(scope.row, scope.$index)">
              {{ scope.row.businessData.contractCode }}
            </el-button>
          </template>
        </el-table-column>
        <template v-for="(table, index) in tableTheadOptions">
          <el-table-column
            :fixed="table.fixed || false"
            :key="index"
            :type="table.type"
            :label="table.label"
            :align="table.align || 'left'"
            :header-align="table.headerAlign || 'left'"
            :min-width="table.width"
            :prop="table.prop"
            :formatter="formatterList[table.formatterName]"
            :show-overflow-tooltip="true"
            border="true"
          >
          </el-table-column>
        </template>
      </el-table>
      <div class="ccui-table-footer" v-show="isShowPagination">
        <div id="ccui-paging">
          <el-pagination
            :total="totalNum"
            :page-size="getLocalPageSize()"
            :current-page="pageNoCode"
            :page-sizes="[10, 20, 50, 100, 200, 500]"
            background
            layout="total, sizes, prev, pager, next, jumper"
            popper-class="ccui-paging-page-size-popper"
            @prev-click="handlePrev"
            @next-click="handleNext"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
          <el-button
            class="ccui-pagination-btn"
            size="mini"
            type="default"
            @click="handleSizeChange('none')"
            >确定</el-button
          >
        </div>
      </div>
    </div>
    <!-- 表格 end -->
  </div>
</template>

<script>
// import draggable from "vuedraggable";
import jsList from "../js";
import { getAllPcconcList } from "../api";
import tabMixin from "../mixins/approval-table";

import {
  setSessionItem,
  getSessionItem,
  removeSessionItem,
  ishasAgentId
} from "@/basa/utils";

export default {
  components: {
    // draggable
  },
  name: "contract-approval-approval",
  mixins: [tabMixin],
  data() {
    return {
      jsList,
      isActive: 0,
      isShowDetail: true,
      isShowEdit: true,
      multiDataToEnd: {},
      singleDataToEnd: {},
      // 表格相关
      tableData: [], // 表格数据
      draggFlag: true,
      tableName: this.tableList.approvalPass, // 表格命名
      tableThead: [], // 表格数据
      // 锁定表格
      fixedTableThead: [
        // {
        //   label: "序号",
        //   prop: "id",
        //   width: "38",
        //   checked: true,
        //   fixed: true,
        //   type: "index",
        //   resizable: false
        // }
      ],
      // 动态表格
      tableTheadOptions: [],
      // 弹框表格
      // popoverShow: false,
      selectRow: [],
      selectData: [],
      isFocus: 1,
      // 表格相关 end
      // 高级搜索数据 start
      formData: {
        contractName: "",
        partyBName: ""
      }, // 高级搜索提交数据
      formDataSearch: "",
      localSearchData: {},
      isShowSearch: true,
      isShow: true,
      // 高级搜索数据 end
      isShowPagination: false, //无数据的不展示底部全选，批量删除
      // 全选以及页码
      totalNum: 0,
      total: 0,
      isIndeterminate: false,
      checkAll: false,
      value: "",
      pageNoCode: this.getLocalPageNo(),
      pageSizeCode: this.getLocalPageSize(),
      // isFist: false,
      // 全选以及页码 end
      // 表格数据删除相关
      delDemoId: "",
      content: "您确定要删除吗？",
      typeDel: "", //有关批量删除
      isSelection: false,
      // 表格数据删除相关 end
      // 排序入参所需字段
      sortord: "",
      sortprop: "",
      // 表格数据相关处理
      formatterList: {
        wirteTimeHandler(row = {}, col) {
          const { businessData = {} } = row;
          const { compileDate = "" } = businessData;
          return compileDate.substr(0, 10);
        },
        apprEndTimeHandler(row, col) {
          return row.apprEndTime ? row.apprEndTime.substr(0, 10) : "";
        },
        deleteTimeHandler(row, col) {
          return row.deleteTime ? row.deleteTime.substr(0, 10) : "";
        },

        isCreated: false
      }
      // 表格数据相关处理 end
    };
  },
  mounted() {
    this.initData();
  },
  methods: {
    initData() {
      this.setTableWidth();
      this.renderTable();
      // this.isFist = false;
    },
    // 默认渲染表格
    renderTable() {
      const localTableData = localStorage.getItem(this.tableName)
        ? JSON.parse(localStorage.getItem(this.tableName))
        : [];
      let unfixedTableThead = this.unfixedTableThead.concat(
        this.fixedTableThead
      );
      let localTableDataStr = localTableData.map(
        ({ label, prop, formatterName, align, width }) =>
          JSON.stringify({ label, prop, formatterName, align, width })
      );
      let unfixedTableTheadStr = unfixedTableThead.map(
        ({ label, prop, width, formatterName, align }) =>
          JSON.stringify({ label, prop, formatterName, align, width })
      );

      if (localTableData.length === unfixedTableThead.length) {
        let flag = localTableDataStr.every(item =>
          unfixedTableTheadStr.includes(item)
        );
        if (flag) {
          // 完全相同
          this.tableTheadOptions = localTableData;
          this.tableThead = localTableData;
          this.unfixedTableThead = localTableData.filter(item => {
            return !this.fixedTableThead.find(
              cItem => item.prop === cItem.prop
            );
          });
        } else {
          // 长度相同但值不同
          this.tableThead = this.unfixedTableThead.concat(this.fixedTableThead);
          const comment = JSON.stringify(this.tableThead);
          localStorage.setItem(this.tableName, comment);
          const localTableData = JSON.parse(
            localStorage.getItem(this.tableName)
          );
          this.tableTheadOptions = localTableData;
        }
      } else {
        // 长度不同
        this.tableThead = this.unfixedTableThead.concat(this.fixedTableThead);
        const comment = JSON.stringify(this.tableThead);
        localStorage.setItem(this.tableName, comment);
        const localTableData = JSON.parse(localStorage.getItem(this.tableName));
        this.tableTheadOptions = localTableData;
      }
    },
    // 表格弹框拖拽触发
    handleTableChange(val) {
      this.tableThead = this.unfixedTableThead.concat(this.fixedTableThead);
      const comment = JSON.stringify(this.tableThead);
      localStorage.setItem(this.tableName, comment);
      const localTableData = JSON.parse(localStorage.getItem(this.tableName));
      this.tableTheadOptions = localTableData;
    },
    // 是否显示对应列
    handleUpdate(item, index) {
      for (let i = 0; i < this.unfixedTableThead.length; i++) {
        if (i === index) {
          this.unfixedTableThead.checked = !this.unfixedTableThead.checked;
        }
      }
      this.tableThead = this.unfixedTableThead.concat(this.fixedTableThead);
      const comment = JSON.stringify(this.tableThead);
      localStorage.setItem(this.tableName, comment);
      const localTableData = JSON.parse(localStorage.getItem(this.tableName));
      this.tableTheadOptions = localTableData;
    },
    // 渲染本地存储表格宽度
    setTableWidth() {
      const localTableData = JSON.parse(localStorage.getItem(this.tableName));
      if (localTableData) {
        for (let i = 0; i < this.tableTheadOptions.length; i++) {
          if (this.tableTheadOptions[i].label === localTableData[i].label) {
            this.tableTheadOptions[i].width = localTableData[i].width;
          }
        }
      }
    },
    // 表格宽度更改存入
    tableTitleWidth(newWidth, oldWidth, column, event) {
      for (let i = 0; i < this.unfixedTableThead.length; i++) {
        if (this.unfixedTableThead[i].label === column.label) {
          this.unfixedTableThead[i].width = newWidth;
        }
      }
      this.tableThead = this.unfixedTableThead.concat(this.fixedTableThead);
      const comment = JSON.stringify(this.tableThead);
      localStorage.setItem(this.tableName, comment);
      this.tableTheadOptions = JSON.parse(localStorage.getItem(this.tableName));
      this.draggFlag = false;
      this.$nextTick(() => {
        this.draggFlag = true;
      });
    },
    // 上一页
    handlePrev() {
      console.log("上一页");
    },
    // 下一页
    handleNext() {
      console.log("下一页");
    },
    // 每页条数发生改变
    handleSizeChange(val) {
      this.pageNoCode = 1;
      if (val !== "none") {
        this.pageSizeCode = val;
        setSessionItem("pageSize", this.tableName, val);
      }
      this.getList(this.formDataSearch);
    },
    // 当前页发生改变
    handleCurrentChange(val) {
      let searchFormData = getSessionItem("pageNo", this.tableName) || {};
      setSessionItem("pageNo", this.tableName, {
        pageNo: val,
        searchForm: searchFormData.searchForm || {}
      });
      this.formDataSearch = {
        ...this.formData
        // ...searchFormData.searchForm
      };
      // 跳转翻页都会调这个方法
      this.pageNoCode = val;
      this.getList(this.formDataSearch);
    },
    // 高级搜索所需函数 start
    // 高级搜索展开按钮
    search(searchData) {
      this.pageNoCode = 1;
      this.formDataSearch = searchData;
      this.localSearchData = JSON.parse(JSON.stringify(searchData));
      setSessionItem("pageNo", this.tableName, {
        pageNo: this.pageNoCode,
        searchForm: this.localSearchData
      });
      this.getList(this.formDataSearch);
    },
    // 高级搜索 end
    // 列表数据请求
    getList(reqObj) {
      console.log(this.pageNoCode);
      let obj = {};
      obj = typeof reqObj == "object" ? reqObj : obj;
      obj.pageNo = this.pageNoCode;
      obj.pageSize = this.pageSizeCode;
      obj.businessBillTypes = this.formData.businessBillTypes
        ? [this.formData.businessBillTypes]
        : [];
      if (this.formData.status == 0) {
        obj.status = this.formData.status;
      }
      obj.isShowPageLoading = true;
      getAllPcconcList(obj)
        .then(res => {
          // console.log(res);
          this.isShowPagination = res.data.data.recordsTotal > 0;
          if (res.data.data.rows.length) {
            // res.data.data.rows.forEach(n => {
            //   // 合同金额（含税）
            //   n.businessData.initTotalContractPriceIncludeTax= Number(
            //     n.businessData.initTotalContractPriceIncludeTax
            //   ).toFixed(2);
            // });
            this.tableData = res.data.data.rows;
          } else {
            this.tableData = [];
          }
          // this.tableData = res.data.data.rows;
          this.totalNum = res.data.data.recordsTotal;
          this.total = res.data.data.total;
          this.pageNoCode = res.data.data.pageNo; // 当前页
        })
        .catch(e => {
          console.log(e);
        });
    },
    // 默认显示多少条
    getLocalPageSize() {
      return getSessionItem("pageSize", this.tableList.approvalPass) || 10;
    },
    // 读取当前页缓存
    getLocalPageNo() {
      let localData = getSessionItem("pageNo", this.tableList.approvalPass);
      return (localData && localData.pageNo) || 1;
    }
  },
  beforeRouteLeave(to, from, next) {
    removeSessionItem("pageNo");
    for (var key in this.$vnode.parent.componentInstance.cache) {
      delete this.$vnode.parent.componentInstance.cache[
        ishasAgentId(to.path, key)
      ];
    }
    next();
  },
  activated() {
    if (Object.keys(this.localSearchData).length > 0) {
      setSessionItem("pageNo", this.tableName, {
        pageNo: this.pageNoCode,
        searchForm: this.localSearchData
      });
    }
    this.formData = {};
    // let localData = getSessionItem("pageNo", this.tableList.approvalPass);
    // let data = localData && localData.searchForm;
    this.getList();
  }
};
</script>
<style lang="scss" scoped>
.contract-approval {
  /deep/ .el-searchs {
    display: none;
  }
  /deep/ .el-search .icon-ccui-downdown {
    display: none;
  }
}
/deep/.ccui-advanced-search-wrapper
  .el-search
  .el-searchs-bottom
  .el-form-item
  .el-form-item__label {
  min-width: 126px !important;
}
</style>
